import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common'
import { Observable, of } from 'rxjs'
import { finalize } from 'rxjs/operators'

// 目前看来有问题，需要验证
@Injectable()
export class RequestQueueInterceptor implements NestInterceptor {
  private static processing = new Set<string>()

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.switchToHttp().getRequest()
    const key = `${req.user?.id ?? req.ip}:${req.method}:${req.path}`

    if (RequestQueueInterceptor.processing.has(key)) {
      console.log('命中锁，直接返回 pending', key)
      return of({ status: 'pending', message: '请求正在处理中' })
    }

    console.log('加锁', key)
    RequestQueueInterceptor.processing.add(key)

    return next.handle().pipe(
      finalize(() => {
        console.log('释放锁', key)
        RequestQueueInterceptor.processing.delete(key)
      }),
    )
  }
}
